package generateConnections;

import java.util.ArrayList;
import java.util.Random;

import networkInterface.NetworkInterfaceBase;

import logging.Logger;

import exception.NoConnectionPossibleException;

import object.Node;
import util.Settings;

public class GenerateRandomConnection extends GenerateConnectionBase {
	
	@Override
	public void genConnections(ArrayList<Node> nodes, Node node) {
		if(r==null)
			r = new Random(Settings.getInstance().getSeed().hashCode());

		resetNodeColors(nodes);
		
		if(nodes.size()==0)
			return;
		int y = 0;
		for(int x = 0; x < Settings.getInstance().getNumRandomConnections(); x++){
			Node n1 = nodes.get(Math.abs(r.nextInt()%(nodes.size())));
			Node n2 = nodes.get(Math.abs(r.nextInt()%(nodes.size())));
			if(n1.getInterfaces().size() > 0 && n2.getInterfaces().size() > 0 && n1 != n2){
				NetworkInterfaceBase i1 = n1.getInterfaces().get(Math.abs(r.nextInt()%(n1.getInterfaces().size())));
				NetworkInterfaceBase i2 = n2.getInterfaces().get(Math.abs(r.nextInt()%(n2.getInterfaces().size())));
				if(i1.canConnect(i2) && i1 != i2){
					try {
						i1.addConnection(i2);
					} catch (NoConnectionPossibleException e) {
						Logger.getInstance().log(Logger.WARNING, "No connection possible shouldn't be thrown " + e.getMessage());
						x--;
					}
				} else {
					x--;
					y++;
					if(y>100){
						x=1000000;
						Logger.getInstance().log(Logger.WARNING, "GenerateRandomConnection Exiting, too many loops");
					}
				}
			} else {
				x--;
				y++;
				if(y>100){
					x=1000000;
					Logger.getInstance().log(Logger.WARNING, "GenerateRandomConnection Exiting, too many loops");
				}
			}
		}
	}

}
